Ext.onReady(function(){

    currYear  = new Date().getFullYear();

    var columnRenderer = function(value){
        var combo = this.editor
        var r = combo.findRecord(combo.valueField, value);
        return r ? r.get(combo.displayField) : combo.valueNotFoundText;
    }

    var dateColumnRenderer =  function(value){
        if (!value) return '';
        if (value instanceof Date) {
            value = value.format('d/m/Y');
            return value;
        }
        try{
            value = Date.parseDate(value, 'Y-m-d').format('d/m/Y');
            return value;
        }catch(e){try{
            value = Date.parseDate(value, 'Y-m-d H:i:s').format('d/m/Y')
            return value;
        }catch(e){
            X.msg.FailureJs(e.message);
        }}
    }

    var hourColumnRenderer =  function(value){
        if(typeof(value) == 'string'){
            var timeDate = new Date().toDateString()+' '+value.slice(0,5);
            value = new Date(timeDate).format('H:i');
            return value;
        }
        return value;
    }

    var h_importar_success = function(obj){
        X.get('importWindow').close();
        window.location = '/calendario';
    }

    X.aStore({
        id     : 'tipoStore',
        fields : [ 'idTipo','nombre' ],
        data   : [ [1,'Vacaciones'],[2,'Suspensión'],[3,'Asueto/Feriado'] ]
    });

    X.store({
        id     : 'importStore',
        fields : [ 'idCalendario', 'descripcion', 'fechaInicio', 'fechaFin',
                   'horaInicio', 'horaFin', 'tipo', 'carrera', 'semestres' ]
    });

    X.store({
        id     : 'storeImportarCarrera',
        fields : ['idCarrera', 'nombre']
    });

    var checkboxSel = new Ext.grid.CheckboxSelectionModel({    });

    var colModel = new Ext.grid.ColumnModel({
        defaults: {
            menuDisabled: true
        },
        columns: [
            checkboxSel,
            {header: 'Fecha inicial', dataIndex: 'fechaInicio', width : 85,
                                  editor: new X.form.date ({id:'inicio'}),
                                  renderer: dateColumnRenderer
            },
            {header: 'Fecha final', dataIndex: 'fechaFin', width : 85,
                                  editor: new X.form.date ({id:'fin'}),
                                  renderer: dateColumnRenderer
            },
            {
              header: 'Desde', dataIndex: 'horaInicio', width : 55,
              editor: new X.form.time({
                          minValue : '0:00 AM',
                          maxValue : '11:59 PM',
                          format   : 'H:i',
                          increment: 30,
                          listWidth: 55
                      })
            },
            {
              header: 'Hasta', dataIndex: 'horaFin', width : 55,
              editor: new X.form.time({
                          minValue : '0:00 AM',
                          maxValue : '11:59 PM',
                          format   : 'H:i',
                          increment: 30,
                          listWidth: 55
                      })
            },
            {header: 'Carrera', dataIndex: 'carrera', width : 135,
                                  editor: new X.form.combo({
                                              dfield  :'nombre',
                                              vfield  :'idCarrera',
                                              storeId :'storeImportarCarrera'
                                          }),
                                  renderer: columnRenderer
            },
            {header: 'Semestres', dataIndex: 'semestres', width : 100,
                                      editor: new X.form.text({
                                                  id:'semestre',
                                                  width:230,
                                                  maxlen: 35
                                              })
            },
            {header: 'Tipo', dataIndex: 'tipo', width : 100,
                                  editor: new X.form.combo({
                                              dfield  :'nombre',
                                              vfield  :'idTipo',
                                              storeId :'tipoStore'
                                          }),
                                  renderer: columnRenderer
            },
            {header: 'Descripción', dataIndex: 'descripcion', width : 170,
                                      editor: new X.form.text({
                                                  id:'descripcion',
                                                  width:230,
                                                  maxlen: 35
                                              })
            }
        ]
    });

    X.grid.panel({
        id          : 'importGrid',
        title       : 'Eventos',
        height      : 261,
        width       : 823,
        cm          : colModel,
        sm          : checkboxSel,
        storeId     : 'importStore',
        x           : 10,
        y           : 45
    });


    X.form.panel({
        id     : 'importForm',
        height : 363,
        width  : 855,
        items  : [
            X.form.label  ({x:10,  y:16,  text:'Año:'}),
            X.form.combo  ({x:50, y:8, width:60,  id:'importAnho', 
                                                   dfield:'years',
                                                   vfield:'years',
                                                   storeId:'yearStore'
                                                   }),
            X.form.label  ({x:128,  y:16,  text:'Nuevo año:'}),
            X.form.combo  ({x:200, y:8, width:60,  id:'nuevoAnho', value: currYear,
                                                   dfield:'years',
                                                   vfield:'years',
                                                   storeId:'yearStore'
                                                   }),
            X.form.hidden ({id:'editorRows'}),
            X.form.button ({x:644, y:320, width:80, id:'importCargar',  text:'Importar'}),
            X.form.button ({x:734, y:320, width:80, id:'importCancelar',  text:'Cancelar'}),
            X.get('importGrid')
        ]
    });

   X.event.button('importCargar', function(){

        var rowCount = X.get('importStore').getCount();

        if (rowCount<=0){
            X.msg.failure('Debe agregar al menos una fecha al calendario');
        }
        else{
            if(X.get('importAnho').getValue()==X.get('nuevoAnho').getValue()){
                X.msg.failure('Debe seleccionar un <b>Nuevo año</b> distinto al original.');
                return;
            }
            var detail = new Array();
            var sc = checkboxSel.getSelections();

            if(sc.length==0){
                X.msg.failure('Debe seleccionar al menos un evento para ser importado al nuevo calendario');
                return;
            }

            for (var i=0; i<sc.length; i++){
                detail.push(sc[i]['data']);
            }
            X.ajax({
                url: '/calendario/ajax-importar',
                params: {
                    anho: X.value('nuevoAnho'),
                    detalles: Ext.encode(detail)
                },
                afterSuccess:h_importar_success
            });
        }
    });

    X.event.button('importCancelar', function(){
        X.get('importWindow').close();
        window.location = '/calendario'
    });

        // WINDOW
    X.win.panel({
        id    : 'importWindow',
        title : 'Importar calendario',
        modal : false,
        items : X.get('importForm')

    });

    X.get('importWindow').begin = function(){
        // el if para asegurar abrir una sola ventana (aunque sea modal)
        if (X.get('importWindow').isVisible()==false){
            X.show('importWindow');
        }
    }

});